package com.cgydu.dao.impl;

import com.cgydu.dao.ProductDao;
import com.cgydu.entity.Product;
import com.cgydu.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * projectName: day25_store
 * author: CGY
 * time: 2020/8/29 10:51
 * description:
 */
public class ProductDaoImpl implements ProductDao {

    @Override
    public List<Product> queryProductByTid(String tid, int currentPage, int pageSize) throws SQLException {

        String sql = "select p_id as pid,t_id as tid,p_name as pname,p_time as ptime ," +
                "p_image as pimage,p_state as pstate ,p_info as pinfo ,p_price as pprice " +
                "from product where t_id = ? limit ?,? ;";



        QueryRunner queryRunner = new QueryRunner(ConnectionUtils.getDataSource());
        List<Product> products = queryRunner.query(sql, new BeanListHandler<Product>(Product.class),
                tid,(currentPage-1)*pageSize,pageSize);

        return products;
    }

    @Override
    public long queryCountByTid(String tid) throws SQLException {

        String sql  = "select count(1) ct from product where t_id = ?;";
        QueryRunner queryRunner = new QueryRunner(ConnectionUtils.getDataSource());
        Long count = (Long) queryRunner.query(sql, new ScalarHandler(),tid);

        return count;
    }

    @Override
    public Product selectProductByPid(String pid) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(ConnectionUtils.getDataSource());
        String sql = "select p_id as pid,t_id as tid,p_name as pname,p_time as ptime ," +
                "p_image as pimage,p_state as pstate ,p_info as pinfo ,p_price as pprice " +
                "from product where p_id = ? ;";

        Product product = queryRunner.query(sql, new BeanHandler<Product>(Product.class), pid);

        return product;
    }
}
